//
//  HAHealthKnowledgeController.swift
//  HealthAide
//
//  Created by rimi on 16/11/7.
//  Copyright © 2016年 赖虹宇. All rights reserved.
//

import UIKit

class HAHealthKnowledgeController: UIViewController ,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
    /// 懒加载
    private lazy var tableView:UITableView = {
        let  tableView = UITableView.init(frame: CGRect(x: 0, y: 64, width: screenW, height: screenH - 44 - 64), style: .plain)
        tableView.rowHeight = 200
        tableView.register(HAHealthHomeCell.self, forCellReuseIdentifier: "HAHealthHomeCell")
        return tableView
    }()
    var btnArr:[UIButton] = []
    var tid :String?
    private var dataArray : [HAHealthKnowlageModel] = []
    var searthTF:UITextField?
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = ""
        automaticallyAdjustsScrollViewInsets = false
        // Do any additional setup after loading the view.
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 200
        addswitchBtn()
        loadData()
        setNavigationSearth()
        addscrollToTopBtn()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searthTF?.isHidden = false
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        searthTF?.isHidden = true
    }
    //MARK:--添加选择器
    func addswitchBtn()  {
        let btnW:CGFloat = 60
        let install = (screenW - margin * 4 - btnW * 4)/3
        let btnBgView = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 44))
        let titleArr = ["养生","用药","心理","保健"]
        for i in 0...3 {
            let btn = UIButton.init(frame: CGRect(x:margin * 2 + (btnW + install) * CGFloat( i ), y: 0, width: btnW, height: 44))
            btn.setTitle(titleArr[i], for: .normal)
            btn.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
            if i == 0 {
                btn.setTitleColor(#colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1), for: .normal)
                btn.isUserInteractionEnabled = false
                tid = "569"
            }
            btn.addTarget(self, action: #selector(switchBtnClicked(sender:)), for: .touchUpInside)
            btnBgView.addSubview(btn)
            btnArr.append(btn)
        }
        tableView.tableHeaderView = btnBgView
    }
    //MARK:--点击按钮回调
    func switchBtnClicked(sender:UIButton)  {
        for btn in btnArr {
            if btn.currentTitle == sender.currentTitle {
                btn.setTitleColor(#colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1), for: .normal)
                btn.isUserInteractionEnabled = false
            }else{
                btn.setTitleColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1), for: .normal)
                btn.isUserInteractionEnabled = true
            }
        }
        let currenttitle = sender.currentTitle ?? ""
        switch currenttitle {
        case "养生":
            tid = "569"
            break
        case "用药":
            tid = "580"
            break
        case "心理":
            tid = "568"
            break
        case "保健":
            tid = "570"
            break
        default:
            break
        }
        loadData()
    }
    //MARK:--点击回到顶部按钮
    func addscrollToTopBtn()  {
        let scrolltopBtn = UIButton.init(frame: CGRect(x: screenW - 80, y: screenH - 100, width: 60, height: 40))
        scrolltopBtn.setTitle("顶部", for: .normal)
        scrolltopBtn.setTitleColor(#colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1), for: .normal)
        scrolltopBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        scrolltopBtn.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
        scrolltopBtn.layer.cornerRadius = 5
        scrolltopBtn.layer.masksToBounds = true
        scrolltopBtn.addTarget(self, action: #selector(clickedscrollToTop), for: .touchUpInside)
        view.addSubview(scrolltopBtn)
    }
    func clickedscrollToTop()  {
//        tableView.scrollToNearestSelectedRow(at: UITableViewScrollPosition.top, animated: true)
        let indexpath = NSIndexPath.init(row: 0, section: 0)
        tableView.scrollToRow(at: indexpath as IndexPath, at: UITableViewScrollPosition.top, animated: true)
    }
    //MARK:--数据源方法
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HAHealthHomeCell", for: indexPath) as! HAHealthHomeCell
        cell.model = dataArray[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
     //MARK:--代理方法
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return dataArray[indexPath.row].cellHight
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let knowledgeVC = HAKnowledgeController()
      knowledgeVC.id = dataArray[indexPath.row].id
        knowledgeVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(knowledgeVC, animated: true)
    }
     //MARK:--数据请求
    func loadData()  {
        dataArray.removeAll()
        let str = tid ?? ""
        let url = "http://route.showapi.com/90-87"
        let prama = ["tid":str,"key":"","page":"1"]
        HANetWorkTools.shared.downloadData(urlStr: url, parameters: prama) {[weak self] (data, error) in
            if error == nil {
                guard  let data = data else {
                    return
                }
                let dict = data as! [String:Any]
                let showapi_res_code = dict["showapi_res_code"] as? Int
                 let code = showapi_res_code ?? -1
                if code == 0 {
                    let  showapi_res_body = dict["showapi_res_body"] as! [String:Any]
                    let  pagebean = showapi_res_body["pagebean"] as! [String:Any]
                    let contentlist = pagebean["contentlist"] as! [[String:Any]]
                    for detaildict in contentlist {
                        let model = HAHealthKnowlageModel(dict: detaildict)
                        self?.dataArray.append(model)
                    }
                    self?.tableView.reloadData()
                }
            }
        }
    }
    //MARK:--添加搜索框
    func setNavigationSearth()  {
        searthTF = UITextField.init(frame: CGRect(x: (screenW - screenW/1.5)/2, y: 5, width: screenW/1.5, height: 34))
        navigationController?.navigationBar.addSubview(searthTF!)
        searthTF?.layer.cornerRadius = 17
        searthTF?.backgroundColor = UIColor.white
        searthTF?.layer.masksToBounds = true
        searthTF?.placeholder = "搜索"
        searthTF?.textAlignment = .center
        searthTF?.delegate = self
    }
    //MARK:-- 搜索框代理方法
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.endEditing(true)
        let  searchVC = HASearchController()
        searchVC.tid = tid
        searchVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(searchVC, animated: true)
    }
}






